// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const { OPENID } = cloud.getWXContext()
const DB1 = cloud.database().collection('wait_pay');
const DB2 = cloud.database().collection('login_coupon');
const _ = cloud.database().command;
// 云函数入口函数
exports.main = async (event, context) => {
  //核对是否满足要求 支付校验
  let return_data, pay_number;
  //需传递参数
  let { pay_money, coupon_id, type } = event;
  if (type == 'hedui') {
    if (coupon_id == '') {
      //没有使用优惠卷
      pay_number = pay_money;
      return_data = { 'code': 200, 'pay_number': pay_number };
      return { coupon_data: '', return_data };
    } else {
      let coupon_data = await (await DB2.doc(coupon_id).get()).data;
      // 判断优惠卷是否过期
      if (coupon_data.over_time >= +new Date()) {
        // 判断类型是否符合
        if (coupon_data.collar_inf.user_type == 'deduction') {
          //需支付金额 - 抵扣
          if (coupon_data.collar_inf.order_number >= pay_money) {
            pay_number = pay_money;
          } else {
            pay_number = Number(pay_money) - Number(coupon_data.collar_inf.order_number);
          }
          return_data = { 'code': 200, 'pay_number': Math.round(pay_number * 100) / 100 };
        } else if (coupon_data.collar_inf.user_type == 'discount') {
          //需支付金额 * 折扣
          pay_number = Number(pay_money) * (Number(coupon_data.collar_inf.order_number) * 0.1);
          return_data = { 'code': 200, 'pay_number': Math.round(pay_number * 100) / 100 };
        }
      } else {
        return_data = { 'code': 400, 'text': '优惠卷已过期！请删除过期优惠卷！' }
      }
      return { coupon_data, return_data };
    }
  } else if (event.type == 'delect') {
    // 删除待支付订单和用户优惠卷。
    let res1, res2;
    if (event.coupon_data_id == '') {
      res1 = await DB1.doc(event.orsder_data_id).remove();
      res2 = '';
    } else {
      res1 = await DB1.doc(event.orsder_data_id).remove();
      res2 = await DB2.doc(event.coupon_data_id).remove();
    }
    return { res1, res2 }
  }

}